package cn.schoolwow.util.module.query.dictionary.service;

import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.util.module.query.dictionary.domain.DictionaryContext;
import cn.schoolwow.util.module.query.dictionary.domain.QueryDictionaryOption;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.Validate;

public class AddDictionaryContextFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        String fieldName = flowContext.checkData("fieldName", String.class);
        String dictionaryValue = flowContext.checkData("dictionaryValue", String.class);
        String replaceFieldName = flowContext.getData("replaceFieldName", String.class);
        QueryDictionaryOption queryDictionaryOption = flowContext.checkInstanceData(QueryDictionaryOption.class);

        String[] tokens = dictionaryValue.split(",", -1);
        JSONObject keyValueMap = new JSONObject();
        for(String token:tokens){
            String key = token.substring(0, token.indexOf(":"));
            String value = token.substring(token.indexOf(":")+1);

            Validate.notEmpty(key, "字典key不能为空");
            Validate.notEmpty(value, "字典值不能为空");
            keyValueMap.put(key, value);
        }

        DictionaryContext dictionaryContext = new DictionaryContext();
        dictionaryContext.replaceFieldName = replaceFieldName;
        dictionaryContext.keyValueMap = keyValueMap;
        dictionaryContext.fieldName = fieldName;
        queryDictionaryOption.dictionaryContextList.add(dictionaryContext);
    }

    @Override
    public String name() {
        return "添加字典上下文值流程";
    }
}
